<script setup name="View2d">
import {
	ref,
	onMounted,
	onActivated,
	onDeactivated,
	computed,
	watch,
	reactive,
	onUnmounted
} from "vue";
import { useRoute } from "vue-router";
import StudyBar from "../components/StudyBar.vue";
import SeriesBar from "../components/SeriesBar.vue";
import DisplayerArea from "../components/DisplayerArea.vue";
// import SystemInfo from "../components/SystemInfo.vue";
import { useArchiveStore } from "../stores/archive";
import { useAppStore } from "../stores/appStore";
import { storeToRefs } from "pinia";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import MainToolbar from "../components/MainToolbar.vue";
import { enableReferenceLines } from "../cornerstone3D/initTools";
import { getCommonInterfacePatientSeriesInfoListByStudyInstanceUID } from "../api/pacs";
import { processDicomUrls } from "../utils/dicomUrlHandler";

const router = useRouter();

const archiveStore = useArchiveStore();
const { seriesList } = storeToRefs(archiveStore);

const appStore = useAppStore();
const route = useRoute();
const view2d = ref(null);
const navDisplay = ref(null);
const studyBar = ref(null);
const seriesBar = ref(null);
const displayArea = ref(null);

// const systemInfo = ref(null);
// const toolbar = ref(null);

const navbarHW = ref(120);
const toolbarHW = ref(420);

const wmFont = reactive({
	color: "rgba(0, 0, 0, .15)"
});

const { toolbarPos, navbarPos } = storeToRefs(appStore);

const mainClass = computed(() => {
	const vorh = toolbarPos.value === "top" ? "vertical" : "horizontal-reverse";
	return "flex-" + vorh;
});

const navDisplayClass = computed(() => {
	const vorh = navbarPos.value === "bottom" ? "vertical" : "horizontal";
	return "flex-" + vorh;
});

const navResizerClass = computed(() => {
	const vorh = navbarPos.value === "bottom" ? "horizontal" : "vertical";
	return "resizer-" + vorh;
});

const navClass = computed(() => {
	return "nav-" + navbarPos.value;
});

const navbarStyle = computed(() => {
	if (navbarPos.value === "bottom") {
		return {
			height: navbarHW.value + "px"
		};
	} else {
		return {
			width: navbarHW.value + "px"
		};
	}
});

watch(toolbarHW, (n, o) => {
	// console.log("toolbarHW changed:", n, o);
	let navDispWidth;
	if (n > o) navDispWidth = navDisplay.value.clientWidth - 2;
	else navDispWidth = navDisplay.value.clientWidth - 1;
	seriesBar.value.setWidth(navDispWidth);
	displayArea.value.setWidth(navDispWidth);
});

watch(
	() => seriesList.value.length,
	(n, o) => {
		// console.log("seriesList changed:", n);
		displayArea.value.displayAuto();
	}
);

function resizeNavbar(e) {
	e.stopPropagation();
	// console.log("resizeNavbar", e.target);
	view2d.value.style.cursor = navbarPos.value === "bottom" ? "ns-resize" : "ew-resize";
	view2d.value.onmousemove = function (e) {
		// console.log("onmousemove", e.movementX, e.movementY);
		let delta, minVal, maxVal;
		if (navbarPos.value === "bottom") {
			delta = -e.movementY;
			minVal = 110;
			maxVal = 165;
		} else {
			delta = e.movementX;
			minVal = 146;
			maxVal = 220;
		}

		// let delta = navbarPos.value === "bottom" ? -e.movementY : e.movementX;
		const value = navbarHW.value + delta;

		if (value < minVal || value > maxVal) return;
		navbarHW.value = value;
		// console.log("navbarHW:", navbarHW.value);
	};

	document.onmouseup = function () {
		// console.log("mouseup");
		view2d.value.onmousemove = null;
		document.onmouseup = null;
		view2d.value.style.cursor = "";
	};
}

const toggleNavbarPos = () => {
	navbarPos.value = navbarPos.value === "bottom" ? "left" : "bottom";
	navbarHW.value = navbarPos.value === "bottom" ? 120 : 146;
	if (navbarPos.value === "bottom") {
		seriesBar.value.setWidth(navDisplay.value.clientWidth);
	}
	// console.log("toggleNavbarPos navbarPos:", navbarPos.value);
	// console.log("toggleNavbarPos appStore.navbarPos:", appStore.navbarPos);
};

const toggleToolbarPos = () => {
	toolbarPos.value = toolbarPos.value === "top" ? "right" : "top";
	toolbarHW.value = toolbarPos.value === "top" ? 146 : 220;
};

async function OnToolbarAction(action) {
	// console.log("OnToolbarAction", action);

	switch (action.name) {
		case "changeToolbarPos":
			toggleToolbarPos();
			break;
		case "changeNavPos":
			toggleNavbarPos();
			break;
		case "openFolder":
			{
				const fileHandles = await openFolder();
				// const dcmfiles = fileHandles.filter(file => file.name.endsWith(".dcm"));
				// console.log("openFolder, fileHandles:", fileHandles);
				if (Array.isArray(fileHandles)) {
					fileHandles.forEach(fileHandle => {
						// const file = await fileHandle.getFile();
						// await archiveStore.archiveFile(file);
						fileHandle.getFile().then(file => {
							archiveStore.archiveFile(file);
						});
					});
				} else {
					// console.error("openFolder, fileHandles is not an array");
				}
			}

			break;
		case "openPacs":
			displayArea.value.showPacsWnd();
			break;
		case "openFile":
			{
				const file = action.files[0];
				archiveStore.archiveFile(file);
			}
			break;
		case "layout":
			console.log("Layout action received:", action.row, action.col);
			displayArea.value.setLayout(action.row, action.col);
			break;
		case "displayAuto":
			displayArea.value.displayAuto();
			break;
		case "clearDisplay":
			displayArea.value.clear();
			break;
		case "deleteViewerMeasure":
			displayArea.value.removeSelectedViewportMeasures();
			break;
		case "colorMap":
			displayArea.value.setViewportColorMap(action.value);
			break;
		case "resetCamera":
			displayArea.value.resetViewportCamera();
			break;
		case "crossline":
			enableReferenceLines(action.checked);
			break;
		case "mprvr":
			show3dView();
			break;
		default:
			break;
	}
}

function show3dView() {
	const imageIds = appStore.currentDisplayer.getImageIds();
	// console.log("show3dView:", imageIds);

	if (imageIds.length > 9) {
		router.push({
			path: "dicom3d"
		});
	} else {
		ElMessage.warning("图像数量过少，无法显示3D视图...");
	}
}

async function openFolder() {
	try {
		// 请求用户选择一个文件夹
		const handle = await showDirectoryPicker();
		const fileHandles = [];
		await processHandle(handle, fileHandles);
		// console.log("handle2:", fileHandles);
		return fileHandles;
	} catch (err) {
		// console.error("无法打开文件夹", err);
		return null;
	}
}

async function processHandle(handle, fileHandles) {
	if (handle.kind === "file") {
		return;
	}
	const itr = await handle.entries();
	for await (const entry of itr) {
		// console.log("entry:", entry);
		if (entry[1].kind === "file" && entry[1].name.toLowerCase().endsWith(".dcm")) {
			fileHandles.push(entry[1]);
		} else {
			await processHandle(entry[1], fileHandles);
		}
	}
}

// 阻止移动端默认触摸行为
function preventTouchDefaults(e) {
	// 只在特定区域阻止默认行为
	const target = e.target;
	const isDisplayArea = target.closest(".display-area");
	const isNavBottom = target.closest(".nav-bottom");
	const isHeadMenubar = target.closest(".head-menubar");
	const isToolbarButton =
		target.closest(".tbbutton") ||
		target.closest(".tbbutton-drop") ||
		target.closest("button");
	const isLayoutWnd = target.closest(".layoutWnd") || target.closest("li[id^='li_']");

	// 如果是工具栏按钮的点击事件，允许通过
	if (e.type === "touchstart" && isToolbarButton) {
		return; // 允许工具栏按钮的点击
	}

	// 如果是布局窗口的触摸事件，允许通过
	if (isLayoutWnd) {
		return; // 允许布局窗口的触摸操作
	}

	// 如果是显示区域的触摸事件，允许缩放操作
	if (isDisplayArea && e.type === "touchmove" && e.touches.length === 2) {
		return; // 允许捏合缩放操作
	}

	// 如果不在允许滚动的区域，阻止默认行为
	if (!isDisplayArea && !isNavBottom && !isHeadMenubar) {
		e.preventDefault();
		e.stopPropagation();
		e.stopImmediatePropagation();
		return false;
	}
}

// 更严格的触摸事件处理 - 阻止所有触摸事件的默认行为
function handleTouchStart(e) {
	preventTouchDefaults(e);
	// 只在需要时阻止默认行为
	const target = e.target;
	const isToolbarButton =
		target.closest(".tbbutton") ||
		target.closest(".tbbutton-drop") ||
		target.closest("button");

	if (!isToolbarButton && e.cancelable) {
		e.preventDefault();
	}
}

function handleTouchMove(e) {
	preventTouchDefaults(e);
	// 只在需要时阻止默认行为
	const target = e.target;
	const isDisplayArea = target.closest(".display-area");

	// 如果是显示区域的捏合缩放操作，允许通过
	if (isDisplayArea && e.touches.length === 2) {
		return; // 允许捏合缩放操作
	}

	// 强制阻止其他触摸移动的默认行为
	if (e.cancelable) {
		e.preventDefault();
	}
}

function handleTouchEnd(e) {
	preventTouchDefaults(e);
}

// 初始化触摸事件处理
function initTouchEvents() {
	const container = view2d.value;
	if (container) {
		// 使用更严格的触摸事件处理
		container.addEventListener("touchstart", handleTouchStart, { passive: false });
		container.addEventListener("touchmove", handleTouchMove, { passive: false });
		container.addEventListener("touchend", handleTouchEnd, { passive: false });
		container.addEventListener("touchcancel", handleTouchEnd, { passive: false });

		// 同时为document添加事件监听器，确保捕获所有触摸事件
		document.addEventListener("touchmove", handleTouchMove, { passive: false });
		document.addEventListener("touchstart", handleTouchStart, { passive: false });
		document.addEventListener("touchend", handleTouchEnd, { passive: false });
		document.addEventListener("touchcancel", handleTouchEnd, { passive: false });

		// 添加全局触摸事件阻止器
		document.body.style.overscrollBehavior = "none";
		document.documentElement.style.overscrollBehavior = "none";
	}
}

// 清理触摸事件
function cleanupTouchEvents() {
	const container = view2d.value;
	if (container) {
		container.removeEventListener("touchstart", handleTouchStart);
		container.removeEventListener("touchmove", handleTouchMove);
		container.removeEventListener("touchend", handleTouchEnd);
		container.removeEventListener("touchcancel", handleTouchEnd);
	}

	// 确保从document中移除所有事件监听器
	document.removeEventListener("touchmove", handleTouchMove);
	document.removeEventListener("touchstart", handleTouchStart);
	document.removeEventListener("touchend", handleTouchEnd);
	document.removeEventListener("touchcancel", handleTouchEnd);

	// 恢复默认的滚动行为
	document.body.style.overscrollBehavior = "";
	document.documentElement.style.overscrollBehavior = "";

	console.log("View2d触摸事件清理完成");
}

onMounted(() => {
	console.log("View2d mounted, 路由参数:", route.query);

	// 初始化触摸事件处理
	setTimeout(() => {
		initTouchEvents();
	}, 100);

	// 支持两种参数名：studyId 或 studyInstanceUID
	const studyInstanceUID = route.query.studyId || route.query.studyInstanceUID;
	console.log("View2d mounted, studyInstanceUID:", studyInstanceUID);

	if (studyInstanceUID) {
		// 使用第三方阅片专用接口获取序列信息
		getCommonInterfacePatientSeriesInfoListByStudyInstanceUID(studyInstanceUID)
			.then(response => {
				console.log("序列信息API响应:", response);
				if (response.status === 200) {
					// 正确的数据结构：response.data.data 才是真正的数组
					const seriesList = response.data.data;
					console.log("序列信息数据:", seriesList);

					// 处理返回的序列信息
					if (Array.isArray(seriesList)) {
						console.log(`获取到 ${seriesList.length} 个序列`);

						// 提取所有DICOM文件URL并加载到显示器中
						const allDicomUrls = [];
						seriesList.forEach(series => {
							if (
								series.dicomFileList &&
								Array.isArray(series.dicomFileList)
							) {
								series.dicomFileList.forEach(file => {
									if (file.url) {
										allDicomUrls.push(file.url);
									}
								});
							}
						});

						console.log(`总共获取到 ${allDicomUrls.length} 个DICOM文件`);

						// 将DICOM文件URL加载到显示器中
						if (allDicomUrls.length > 0) {
							// 使用工具函数处理所有URL
							const processedUrls = processDicomUrls(allDicomUrls);

							processedUrls.forEach(dcmUrl => {
								console.log("加载DICOM文件:", dcmUrl);
								archiveStore.archiveFile(dcmUrl);
							});
							console.log(
								`成功加载 ${processedUrls.length} 个DICOM文件到显示器中`
							);
						} else {
							console.warn("没有找到DICOM文件URL");
						}
					} else {
						console.error("API返回的数据不是数组:", seriesList);
					}
				} else {
					console.error("API调用失败:", response);
				}
			})
			.catch(error => {
				console.error("获取序列信息失败:", error);
			});
	} else {
		console.warn("View2d mounted: 没有找到studyId或studyInstanceUID参数");
	}
});

onActivated(() => {
	console.log("View2d activated");
	setTimeout(() => {
		displayArea.value.displayAuto();
		// 重新初始化触摸事件
		initTouchEvents();
	}, 300);
});

// 组件停用时清理事件监听器
onDeactivated(() => {
	console.log("View2d deactivated, cleaning up touch events");
	cleanupTouchEvents();
});

// 组件卸载时清理事件监听器
onUnmounted(() => {
	cleanupTouchEvents();
});
</script>

<template>
	<el-watermark :font="wmFont" :content="[]">
		<div class="container flex-vertical" ref="view2d" @contextmenu.prevent>
			<div class="head-menubar">
				<MainToolbar ref="mainToolbar" @action="OnToolbarAction" />
			</div>
			<div class="header flex-horizontal">
				<!-- <div class="logo">
					<SystemInfo ref="systemInfo" />
				</div> -->
				<div class="study-list">
					<!-- Study List -->
					<StudyBar ref="studyBar" />
				</div>
			</div>
			<div class="main" :class="mainClass">
				<div class="nav-display" :class="navDisplayClass" ref="navDisplay">
					<template v-if="navbarPos === 'bottom'">
						<div class="display-area">
							<DisplayerArea ref="displayArea" />
						</div>
						<div :class="navResizerClass" @mousedown="resizeNavbar"></div>
						<div :class="navClass" :style="navbarStyle">
							<SeriesBar ref="seriesBar" />
						</div>
					</template>
					<template v-else>
						<div :class="navClass" :style="navbarStyle">
							<SeriesBar ref="seriesBar" />
						</div>
						<div :class="navResizerClass" @mousedown="resizeNavbar"></div>
						<div class="display-area">
							<DisplayerArea ref="displayArea" />
						</div>
					</template>
				</div>
			</div>
			<div class="footer"></div>
		</div>
	</el-watermark>
</template>

<style scoped lang="scss">
$bg-color: #333;
$main-color: lightblue;
$header-color: #45b7ec;
$footer-color: #45b7ec;
$resizer-width: 2px;
$header-height: 100px;
$footer-height: 34px;

.container {
	background-color: var(--color-theme-bg);
	height: 100vh;
	width: 100vw;
	max-width: 100%;
	max-height: 100%;
	justify-content: center;
	color: var(--color-theme-text);
	user-select: none;
	overflow: auto;
}

.flex-vertical {
	display: flex;
	flex-direction: column;
}

.flex-vertical-reverse {
	display: flex;
	flex-direction: column-reverse;
}

.flex-horizontal {
	display: flex;
	flex-direction: row;
}

.flex-horizontal-reverse {
	display: flex;
	flex-direction: row-reverse;
}

.resizer-vertical {
	cursor: ew-resize;
	width: $resizer-width;
	background-color: gray;
	flex-shrink: 0;
	z-index: 10;
}

.resizer-horizontal {
	cursor: ns-resize;
	height: $resizer-width;
	background-color: gray;
	width: 100%;
	flex-shrink: 0;
	z-index: 10;
}

.header {
	height: $header-height;
	border-bottom: gray solid 1px;

	.logo {
		height: 100%;
		width: 200px;
		border-right: gray solid 1px;
		flex-shrink: 0;
	}

	.study-list {
		flex: 1;
		height: 100%;
	}
}

.main {
	width: 100%;
	flex: 1;

	.nav-display {
		flex: 1;
	}

	.toolbar-top {
		height: 200px;
		width: 100%;
	}

	.toolbar-right {
		width: 200px;
		height: 100%;
		flex-shrink: 0;
	}

	.nav-display {
		.display-area {
			flex: 1;
			flex-shrink: 0;
		}
		.nav-left {
			height: 100%;
		}

		.nav-bottom {
			width: 100%;
			overflow-x: auto !important;
			min-width: max-content !important;
			display: flex;
			flex-direction: column;
		}
	}
}

.footer {
	height: $footer-height;
	border-top: gray solid 1px;
}

/* 移动端响应式设计 */
@media (max-width: 768px) {
	.container {
		height: 100vh;
		width: 100vw;
		overflow: hidden;
	}

	.head-menubar {
		min-height: 45px;
		height: auto; /* 自适应高度 */
		overflow-y: auto;
	}

	.header {
		height: 60px;
		min-height: 60px;

		.logo {
			width: 120px;
		}
	}

	.main {
		.nav-display {
			.nav-left {
				width: 120px !important;
				min-width: 120px;
			}

			.nav-bottom {
				height: 100px !important;
				min-height: 100px;
				overflow-x: auto;
			}
		}
	}

	.footer {
		height: 24px;
		min-height: 24px;
	}
}

/* 超小屏幕手机 (320px - 480px) */
@media (max-width: 480px) {
	.header {
		height: 50px;
		min-height: 50px;

		.logo {
			width: 100px;
		}
	}

	.head-menubar {
		min-height: 40px;
		height: auto; /* 自适应高度 */
	}

	.main {
		.nav-display {
			.nav-left {
				width: 100px !important;
				min-width: 100px;
			}

			.nav-bottom {
				height: 80px !important;
				min-height: 80px;
				overflow-x: auto;
			}
		}
	}

	.footer {
		height: 20px;
		min-height: 20px;
	}
}

/* 平板设备适配 (769px - 1024px) */
@media (min-width: 769px) and (max-width: 1024px) {
	.header {
		height: 80px;
		min-height: 80px;

		.logo {
			width: 160px;
		}
	}

	.head-menubar {
		min-height: 50px;
		height: auto; /* 自适应高度 */
	}

	.main {
		.nav-display {
			.nav-left {
				width: 160px !important;
				min-width: 160px;
			}

			.nav-bottom {
				height: 120px !important;
				min-height: 120px;
				overflow-x: auto;
			}
		}
	}

	.footer {
		height: 28px;
		min-height: 28px;
	}
}

/* 大屏幕平板/小桌面 (1025px - 1366px) */
@media (min-width: 1025px) and (max-width: 1366px) {
	.header {
		height: 90px;
		min-height: 90px;

		.logo {
			width: 180px;
		}
	}

	.head-menubar {
		min-height: 55px;
		height: auto; /* 自适应高度 */
	}

	.main {
		.nav-display {
			.nav-left {
				width: 180px !important;
				min-width: 180px;
			}

			.nav-bottom {
				height: 140px !important;
				min-height: 140px;
				overflow-x: auto;
			}
		}
	}

	.footer {
		height: 30px;
		min-height: 30px;
	}
}

/* 触摸设备优化 */
@media (hover: none) and (pointer: coarse) {
	/* 在移动端，为整个页面设置禁止滚动 */
	html,
	body {
		overflow: hidden;
		touch-action: none;
		-webkit-overflow-scrolling: none;
		overscroll-behavior: none;
		position: fixed;
		width: 100%;
		height: 100%;
	}

	.container {
		touch-action: none; /* 禁止所有触摸滚动 */
		-webkit-overflow-scrolling: touch;
		overscroll-behavior: none; /* 禁止过度滚动效果 */
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		width: 100vw;
		height: 100vh;
		overflow: hidden;
	}

	/* 允许显示区域进行触摸操作 */
	.display-area {
		touch-action: pan-x pan-y pinch-zoom; /* 允许平移和缩放 */
		-webkit-overflow-scrolling: touch;
	}

	/* 允许导航栏水平滚动 */
	.nav-bottom {
		touch-action: pan-x; /* 只允许水平滚动 */
		-webkit-overflow-scrolling: touch;
		overflow-x: auto;
	}

	/* 允许工具栏垂直滚动 */
	.head-menubar {
		touch-action: pan-y; /* 只允许垂直滚动 */
		-webkit-overflow-scrolling: touch;
		overflow-y: auto;
	}

	.resizer-vertical,
	.resizer-horizontal {
		min-width: 8px;
		min-height: 8px;
		touch-action: none; /* 调整器不允许触摸操作 */
	}
}

/* 横屏模式优化 */
@media (orientation: landscape) and (max-width: 768px) {
	.header {
		height: 50px;
		min-height: 50px;
	}

	.head-menubar {
		min-height: 40px;
		height: auto; /* 自适应高度 */
	}

	.main {
		.nav-display {
			.nav-left {
				width: 120px !important;
				min-width: 120px;
			}

			.nav-bottom {
				height: 90px !important;
				min-height: 90px;
				overflow-x: auto;
			}
		}
	}
}
</style>
